package com.woniuxy.exam.controller;

import com.itextpdf.text.DocumentException;
import com.woniuxy.commons.entity.Paper;
import com.woniuxy.commons.entity.PaperStructure;
import com.woniuxy.commons.entity.ResponseEntity;
import com.woniuxy.exam.entity.PaperDto;
import com.woniuxy.exam.mapper.PaperMapper;
import com.woniuxy.exam.service.PaperService;
import com.woniuxy.exam.service.PaperStructureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.List;


/**
 * @Author 余枭春
 * @Date 2020/7/16 19:02
 * @Description 试卷业务层
 **/
@RestController
public class PaperController {

    @Autowired
    private PaperService paperService;
//=================================================================
//这一段为试卷基本信息
//=================================================================

    /**
     * 提供所有试卷基本
     *
     * @return
     */
    @RequestMapping("/paper/all")
    public ResponseEntity<List<Paper>> allPaper() {
        return new ResponseEntity<List<Paper>>(200, "ok", paperService.allPaper());
    }

    @PostMapping("/paper/allWithConditions")
    public ResponseEntity<List<Paper>> allPaperWithConditions(@RequestBody Paper paper) {
        return new ResponseEntity<List<Paper>>(200, "ok", paperService.allPaperWithConditions(paper));
    }

    /**
     * 根据具体的试卷id可以获取试卷
     *
     * @param paperId
     * @return
     */
    @RequestMapping("/paper/find/{paperId}")
    public ResponseEntity<Paper> findPaperByPaperId(@PathVariable("paperId") int paperId) {
        return new ResponseEntity<Paper>(200, "ok", paperService.findPaper(paperId));
    }

    /**
     * 根据前端的信息创建一个试卷类，成功返回试卷的id,
     *
     * @param paper
     * @return
     */
    @PostMapping("/paper/create")
    public ResponseEntity<Integer> createPaper(@RequestBody Paper paper) {
        //
        int res = 0;
        if (paper.getId() != 0) {
            //TODO 更新试卷基本信息
            res = paperService.updatePaper(paper);
        }
        res = paperService.createPaper(paper);
        if (res > 0) {
            return new ResponseEntity<>(200, "ok", res);
        }
        return new ResponseEntity<>(500, "失败TAT", null);
    }

    /**
     * 更新试卷状态，发布或不发布
     *
     * @param status
     * @param paperId
     * @return
     */
    @GetMapping("/paper/updateStatus/{status}/{Paperid}")
    public ResponseEntity<Integer> update(@PathVariable("status") Integer status, @PathVariable("Paperid") Integer paperId) {
        if (status == 1 || status == 2) {
            int res = paperService.updatePaperStatus(status, paperId);
            if (res == -1) {
                return new ResponseEntity<>(500, "试卷不存在", null);
            }
            if (res > 0) {
                return new ResponseEntity<>(200, "ok", paperId);
            }
            return new ResponseEntity<>(500, "系统出错", null);
        } else {
            return new ResponseEntity<>(500, "状态码错误", null);
        }
    }
//=================================================================
//这一段为试卷结构设定
//=================================================================

    @Autowired
    private PaperStructureService paperStructureService;

    /**
     * 设定试卷结构
     *
     * @param paperStructure
     * @return
     */
    @PostMapping("/paper/insertStructure")
    public ResponseEntity<Integer> insertPaperStructure(@RequestBody PaperStructure paperStructure) {
        System.out.println(paperStructure);
        int res = paperStructureService.insertPaperStructure(paperStructure);
        if (res > 0) {
            return new ResponseEntity<>(200, "ok", null);
        }
        return new ResponseEntity<>(500, "系统正在维护，请稍后访问");
    }

    /**
     * 通过试卷id获取相应的试卷结构
     *
     * @param paperId
     * @return
     */
    @GetMapping("/paper/getStructure/{paperId}")
    public ResponseEntity<PaperStructure> findPaperStructureByPaperId(@PathVariable("paperId") int paperId) {
        PaperStructure res = paperStructureService.findPaperStructureByPaperId(paperId);
        if (res == null) {
            return new ResponseEntity<>(500, "没有该试卷", null);
        }
        return new ResponseEntity<>(200, "ok", res);
    }

//=================================================================
//这一段为试卷与试题绑定
//=================================================================

    /**
     * 自动组卷
     *
     * @param paperDto
     * @return
     */
    @PostMapping("/paper/completePaperAuto")
    public ResponseEntity<Integer> completePaperAuto(@RequestBody PaperDto paperDto) {
        int res = paperService.completePaperAuto(paperDto);
        if (res < -1 || res == 0) {
            return new ResponseEntity<>(500, "系统正在休息，请稍后访问哦", null);
        }
        if (res == -1) {
            return new ResponseEntity<>(500, "请选则题库", null);
        }

        return new ResponseEntity<>(200, "ok", null);
    }

    /**
     * 手动组卷
     *
     * @param paperDto
     * @return
     */
    @PostMapping("/paper/completePaper")
    public ResponseEntity<Integer> completePaper(@RequestBody PaperDto paperDto) {
        int res = paperService.completePaper(paperDto);
        System.out.println("-------------" + res + "---------");
        if (res == 3) {
            //TODO 修改code
            return new ResponseEntity<>(201, "已经转换为自动组卷哦", null);
        }
        if (res > 0) {
            return new ResponseEntity<>(200, "ok", null);
        }
        return new ResponseEntity<>(500, "系统正在休息，请稍后访问哦", null);
    }

//=================================================================
//这一段为获取到具体的试卷和试题
//=================================================================

    /**
     * 通过试卷id获取具体的试卷结构
     *
     * @param paperId
     * @return
     */
    @GetMapping("/paper/fullPaper/{paperId}")
    public ResponseEntity<PaperDto> getFullPaper(@PathVariable("paperId") int paperId) {
        System.out.println(paperId);
        PaperDto paperDto = paperService.getFullPaper(paperId);
      //  System.out.println(paperDto.toString());
      //  return null;
       return new ResponseEntity<>(200, "ok", paperDto);
    }

    //=================================================================
//这一段为打印试卷
//=================================================================
    @GetMapping("/paper/printPaper/{paperId}")
    public org.springframework.http.ResponseEntity<byte[]> printPaper(@PathVariable("paperId") int paperId, HttpServletResponse response, HttpServletRequest request) throws IOException, DocumentException {
        //获取文件存储路径
        String res = paperService.printPaper(paperId);

        System.out.println(res);
        if (res.contains("%")) {
            try {
                res = URLDecoder.decode(res, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                System.out.println("responseFileStream decode error:" + e.toString());
            }
        }
        System.out.println(res);
        FileInputStream in = null;
//        try {
            in = new FileInputStream(new File(res));
            String[] dir = res.split("/");
            String fileName = dir[dir.length - 1];
            HttpHeaders headers = new HttpHeaders();

            headers.add("Content-Type", "application/octet-stream");
            headers.add("Content-Disposition", "attachment;filename=" + fileName);
            //设置文件头：最后一个参数是设置下载文件名

            byte[] data = new byte[in.available()];
            in.read(data);

            in.close();

             return new org.springframework.http.ResponseEntity<byte[]>(data,headers, HttpStatus.OK);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return new org.springframework.http.ResponseEntity<byte[]>(null);

    }


}
